import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, asyncRouter, anyRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    // 保存当前返回的所有的权限数组
    routers: [],
    // 对比之后的路由【 服务器返回的路由和项目中的路由进行对比】
    resultRoutes: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTES: (state, routers) => {
    state.routers = routers
  },
  //
  RESULTROUTES: (state, resultRoutes) => {
    state.resultRoutes = resultRoutes
  }
}
// 这里的路由和index里的路由不对，，所以 没写完，整体逻辑就是   对比之后 在把所有的路由cancat 然后调用router.addRoutes()，然后找到侧边栏 遍历vueX里面的routers
const computedAsyncRoute = (asyncRouter, routes) => {
  return asyncRouter.filter((item) => {
    if (routes.indexOf(item.name) !== -1) {
      if (item.children && item.children.length) {
        item.children = computedAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    const res = await login({ username, password })
    if (res.code == 20000) {
      console.log(res)
      console.log(222222222222222222222222)
      commit('SET_TOKEN', res.data.token)
      setToken(res.data.token)
    }
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        console.log('xxxx', response)
        if (!data) {
          return reject('失败， 请重登录.')
        }
        const { name, avatar, routes } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_ROUTES', routes)
        commit('RESULTROUTES', computedAsyncRoute(asyncRouter, routes))
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

